"""
datakit执行公共函数
"""

from yat.test import Node

from testcase.utils.datakit_api.CommonApi import CommonApi
from .Logger import Logger


class CommonDatakit:
    def __init__(self, token, node='datakit'):
        self.token = token
        self.com_api = CommonApi(token)
        self.log = Logger()
        self.node = Node(node=node)

    def import_host(self, node_list: list):
        """
        快速导入服务器,如果服务器已存在则导入用户
        :param node_list: 需要导入的服务器节点的列表
        :return:
        """
        for node in node_list:
            response = self.com_api.get_host_page(name=f"{node.ssh_host}")
            self.log.info(response.json())
            if response.json()['total'] == 1:
                host_id = response.json()['rows'][0]['hostId']
                response = self.com_api.get_hostUser_page(host_id)
                self.log.info(response.json())
                if any(item['username'] == node.ssh_user for item in response.json()['rows']):
                    self.log.info(f"主机 {host_id} 已存在用户 {node.ssh_user}，跳过配置")
                    continue
                use_msg = {"hostId": f"{host_id}", "username": f"{node.ssh_user}",
                           "password": f"{node.ssh_password}"}
                self.log.info(use_msg)
                response = self.com_api.post_hostUser(use_msg)
                self.log.info(response.json())
                response = self.com_api.get_hostUser_page(host_id)
                self.log.info(response.json())
                assert response.text.find(node.ssh_user) >= -1
            else:
                data = {"hostId": "",
                        "isRemember": True,
                        "name": f"{node.ssh_host}",
                        "password": f"{node.ssh_password}",
                        "port": 22,
                        "privateIp": f"{node.ssh_host}",
                        "publicIp": f"{node.ssh_host}",
                        "remark": "",
                        "tags": [],
                        "username": f"{node.ssh_user}"}
                response = self.com_api.post_host(data)
                self.log.info(response.json())
                assert response.json()['code'] == 200
                response = self.com_api.get_host_page(name=f"{node.ssh_host}")
                self.log.info(response.json())
                assert response.json()['total'] == 1

    def delete_host(self):
        """
        快速删除已导入的服务器
        :return:
        """
        response = self.com_api.get_host_page()
        self.log.info(response.json())
        for cluster in response.json()['rows']:
            response = self.com_api.delete_host(cluster['hostId'])
            self.log.info(response.json())
            assert response.json()['code'] == 200
        res = self.com_api.get_host_page()
        self.log.info(res.json())
        return res

    def import_db(self, db_node_list: list):
        """
        快速导入数据库实例
        :param db_node_list: 数据库节点列表
        :return:
        """
        for db_node in db_node_list:
            if db_node.db_type == 'mysql':
                data = {"clusterName": f"{db_node.ssh_host}({db_node.db_port})-1",
                        "dbType": "MYSQL", "deployType": "SINGLE_NODE",
                        "nodes": [{"id": "", "tabName": 1,
                                   "url": f"jdbc:mysql://{db_node.ssh_host}:{db_node.db_port}",
                                   "urlSuffix": "", "ip": f"{db_node.ssh_host}",
                                   "port": db_node.db_port,
                                   "username": f"{db_node.db_user}",
                                   "password": f"{db_node.db_password}",
                                   "props": [{"name": "", "value": ""}], "status": 1,
                                   "extendProps": "[{\"name\":\"\",\"value\":\"\"}]"}]}
                self.log.info(data)
            else:
                data = {"clusterName": f"{db_node.ssh_host}({db_node.db_port})-1",
                        "dbType": "OPENGAUSS",
                        "deployType": "SINGLE_NODE",
                        "nodes": [{"id": "", "tabName": 1,
                                   "url": f"jdbc:opengauss://{db_node.ssh_host}:{db_node.db_port}/postgres",
                                   "urlSuffix": "", "ip": f"{db_node.ssh_host}",
                                   "port": db_node.db_port,
                                   "username": f"{db_node.db_user}",
                                   "password": f"{db_node.db_password}",
                                   "props": [{"name": "", "value": ""}], "status": 1,
                                   "extendProps": "[{\"name\":\"\",\"value\":\"\"}]"}]}
                self.log.info(data)
            response = self.com_api.post_jdbcDbCluster_add(data)
            self.log.info(response.json())
            assert response.json()['code'] == 200
            response = self.com_api.get_jdbcDbCluster_page(ip=db_node.ssh_host)
            self.log.info(response.json())
            assert response.json()['rows'] is not None

    def delete_db(self):
        """
        快速删除实例
        :return:
        """
        response = self.com_api.get_jdbcDbCluster_page()
        self.log.info(response.json())
        if response.json()['rows'] is None:
            return
        for db_cluster_msg in response.json()['rows']:
            for db_node in db_cluster_msg['nodes']:
                cluster_node_id = db_node['clusterNodeId']
                response = self.com_api.delete_jdbcDbCluster(cluster_node_id)
                self.log.info(response)
                assert response.json()['code'] == 200
        response = self.com_api.get_jdbcDbCluster_page()
        self.log.info(response.json())
        assert response.json()['rows'] == []

    def join_pkg_url(self, node, db_version, pkg_version):
        url = None
        cmd1 = 'cat /etc/system-release'
        cmd2 = 'arch'
        self.log.info(cmd1)
        sys_res = node.sh(cmd1).result()
        self.log.info(sys_res)
        self.log.info(cmd2)
        arch_res = node.sh(cmd2).result()
        self.log.info(arch_res)
        if db_version in ('6.0.0', '7.0.0-RC1'):
            os_lable = 'openEuler' if 'openEuler' in sys_res else 'CentOS'
            os_version = '20.03' if '20.03' in sys_res else '22.03' \
                if '22.03' in sys_res else '24.03' \
                if '24.03' in sys_res else '7'
            arch_str = 'arm' if 'aarch64' in arch_res else 'x86'
            if pkg_version == 'MINIMAL_LIST':
                url = f'{db_version}/{os_lable}{os_version}/{arch_str}/' \
                      f'openGauss-Server-{db_version}-{os_lable}{os_version}-' \
                      f'{arch_res}.tar.bz2'
            elif pkg_version == 'LITE':
                url = f'{db_version}/{os_lable}{os_version}/{arch_str}/' \
                      f'openGauss-Lite-{db_version}-{os_lable}{os_version}-' \
                      f'{arch_res}.tar.gz'
            else:
                url = f'{db_version}/{os_lable}{os_version}/{arch_str}/' \
                      f'openGauss-All-{db_version}-{os_lable}{os_version}-' \
                      f'{arch_res}.tar.gz'
        elif db_version == '6.0.0-RC1':
            if arch_res == 'x86_64':
                if 'openEuler' in sys_res:
                    os_lable = 'openEuler'
                    if '20.03' in sys_res:
                        os_version = 'x86_openEuler'
                    elif '22.03' in sys_res:
                        os_version = 'x86_openEuler_2203'
                    else:
                        raise Exception('无适配当前环境的安装包，请更换环境后重试')
                else:
                    os_lable = 'CentOS'
                    os_version = 'x86'
            else:
                if 'openEuler' in sys_res:
                    os_lable = 'openEuler'
                    if '20.03' in sys_res:
                        os_version = 'arm'
                    elif '22.03' in sys_res:
                        os_version = 'arm_2203'
                    else:
                        raise Exception('无适配当前环境的安装包，请更换环境后重试')
                else:
                    os_lable = 'CentOS'
                    os_version = 'x86'
            if pkg_version == 'MINIMAL_LIST':
                url = f'{db_version}/{os_version}/' \
                      f'openGauss-{db_version}-{os_lable}-64bit.tar.bz2'
            elif pkg_version == 'LITE':
                url = f'{db_version}/{os_version}/' \
                      f'openGauss-Lite-{db_version}-{os_lable}-{arch_res}.tar.gz'
            else:
                url = f'{db_version}/{os_version}/' \
                      f'openGauss-{db_version}-{os_lable}-64bit-all.tar.gz'
        elif db_version in (
                '5.1.0', '5.0.3', '5.0.2', '5.0.1', '5.0.0', '3.1.1'):
            if arch_res == 'x86_64':
                if 'openEuler' in sys_res:
                    if '20.03' in sys_res:
                        os_version = 'x86_openEuler'
                    elif '22.03' in sys_res:
                        os_version = 'x86_openEuler_2203'
                    else:
                        raise Exception('无适配当前环境的安装包，请更换环境后重试')
                else:
                    os_version = 'x86'
            else:
                if 'openEuler' in sys_res:
                    if '20.03' in sys_res:
                        os_version = 'arm'
                    elif '22.03' in sys_res:
                        os_version = 'arm_2203'
                    else:
                        raise Exception('无适配当前环境的安装包，请更换环境后重试')
                else:
                    os_version = 'x86'
            os_lable = 'openEuler' if 'openEuler' in sys_res else 'CentOS'
            if pkg_version == 'MINIMAL_LIST':
                url = f'{db_version}/{os_version}/' \
                      f'openGauss-{db_version}-{os_lable}-64bit.tar.bz2'
            elif pkg_version == 'LITE':
                url = f'{db_version}/{os_version}/' \
                      f'openGauss-Lite-{db_version}-{os_lable}-{arch_res}.tar.gz'
            else:
                url = f'{db_version}/{os_version}/' \
                      f'openGauss-{db_version}-{os_lable}-64bit-all.tar.gz'
        return url

    def get_os_info(self, node):
        info = dict()
        cmd = 'cat /etc/system-release'
        self.log.info(cmd)
        sys_res = node.sh(cmd).result()
        self.log.info(sys_res)
        info['os'] = 'openEuler' if 'openEuler' in sys_res else 'CentOS'
        info['os_version'] = '20.03' if '20.03' in sys_res else '22.03' \
            if '22.03' in sys_res else '24.03' if '24.03' in sys_res else '7'
        info['cpu_arch'] = node.sh('arch').result()
        return info


